package com.easylinkin.linkappapi.blockqueue;

import java.util.concurrent.ThreadPoolExecutor;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

/**
 * @author xiaoyang
 * @version 1.0
 * @date 2023/08/14
 * @description 阻塞队列监听器
 */
@Slf4j
@Component
public class BlockingQueueListener implements ApplicationListener<ApplicationStartedEvent>{

  private static final int corePoolSize = 15;
  static ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
  static {
    threadPoolTaskExecutor.setCorePoolSize(corePoolSize);
    threadPoolTaskExecutor.setMaxPoolSize(25);
    threadPoolTaskExecutor.setQueueCapacity(100);
    threadPoolTaskExecutor.setThreadNamePrefix("blockingQueueListener-pool-");
    threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
    threadPoolTaskExecutor.afterPropertiesSet();
  }

  @Resource
  private BlockingQueueConsumer blockingQueueConsumer;

  @Override
  public void onApplicationEvent(ApplicationStartedEvent event) {
    for (int i = 0; i < corePoolSize; i++){
      threadPoolTaskExecutor.submit(blockingQueueConsumer);
    }
  }
}
